package cn.ffcs.tmp.listener;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.InputStream;
import java.util.Date;
import java.util.Timer;
import java.util.Vector;

import javax.servlet.ServletContext;
import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;

import org.springframework.web.context.WebApplicationContext;
import org.springframework.web.context.support.WebApplicationContextUtils;

import lotus.domino.*;

import org.apache.commons.beanutils.PropertyUtils;
import org.apache.struts.action.Action;

import cn.ffcs.common.model.Attach;
import cn.ffcs.common.service.AttachService;
import cn.ffcs.tmp.dao.AnnexDAO;
import cn.ffcs.tmp.model.Annex;
import cn.ffcs.tmp.service.AnnexService;
import cn.ffcs.tmp.service.IAnnexService;
import cn.ffcs.tmp.web.AnnexAction;

public class DominoListener implements ServletContextListener 
{
    private Session session;
    private String message;
    private Timer timer=null;
    private final String ior = "IOR:010000002900000049444c3a6c6f7475732f646f6d696e6f2f636f7262612f494f626a6563745365727665723a312e3000000000010000000000000078000000010101001300000068647a782e666a74656c65636f6d2e636f6d0000f4ea0000310000000438353235363531612d656336382d313036632d656565302d303037653264323233336235004c6f7475734e4f490100010000000100000001000000140000000100000001000105000000000001010000000000";

    
    public void contextDestroyed(ServletContextEvent arg0)
    {
        // TODO Auto-generated method stub
        if (timer != null) timer.cancel();
    }

    class TimerTask extends java.util.TimerTask
    {
        private ServletContext servletContext = null;
        private WebApplicationContext ctx = null;
        private IAnnexService annexService=null;
        
        public TimerTask(ServletContext servletContext)
        {
            this.servletContext = servletContext;
            ctx=(WebApplicationContext)servletContext.getAttribute(WebApplicationContext.ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE);
            annexService=(AnnexService)ctx.getBean("AnnexService");
        }
        
        public void run()
        {
            // TODO Auto-generated method stub
//          ctx=(WebApplicationContext)servletContext.getAttribute(WebApplicationContext.ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE);
            System.out.println ("开始线程");
            try
            {
                linkDomino();
            }
            catch (Exception n)
            {
                n.printStackTrace();
            }
            System.out.println ("线程结束");
        }
        
        /**
         * 连接domino服务器，把附件同步到数据库中
         * TODO 请输入方法说明
         */
        public synchronized void linkDomino(){
            try{
                Session session = NotesFactory.createSessionWithIOR(ior);
                // //*创建新会话对象
                // 获取数据库及日志参数
                Database oadb = session.getDatabase(null, "dx_yunyzxjk.nsf");
                View view = oadb.getView("Yunyzxjk");
                Document doc = view.getFirstDocument();
                System.out.println("start "+new Date());
                Annex annex;
                while (doc != null)
                {
                    RichTextItem aa=(RichTextItem)doc.getFirstItem("Body");
                    Vector objs=aa.getEmbeddedObjects();
                    EmbeddedObject eo;
                    boolean flag=false;
                    Item item=doc.getFirstItem("Fujm");
                    Vector fujms=item.getValues();
                    if(objs!=null&&fujms!=null&&fujms.size()>0&&fujms.size()==objs.size()){
                        flag=true;
                    }

                    annex=new Annex();
                    annex.setFileType("FILE");
                    annex.setPrefix("file");
                    annex.setName(doc.getItemValueString("Biaot"));
                    annex.setCreator((doc.getItemValueString("Zhuangr") == null) ? ""
                                    : doc.getItemValueString("Zhuangr"));
                    annex.setRefEntity(annex.getClass().getName());
                    annex.setRefEntityID("1");
                    annex.setIsPublish(0);
                    
                    for (int i = 0; i < objs.size(); i++){
                        
                        eo=(EmbeddedObject)objs.get(i);
                        InputStream input =eo.getInputStream();
                        ByteArrayOutputStream os = new ByteArrayOutputStream();
                        
                        int len=64*1024;
                        int count=-1;
                        byte[] buffer = new byte[len];
                        while((count=input.read(buffer,0,len))>-1){
                            os.write(buffer,0,count);
                        }
                        byte a[] = os.toByteArray();
                        
                        annex.setId(null);
                        annex.setContent(a);
                        if(flag){
                            annex.setFullName(procString(fujms.get(i)+""));
                        }else{
                            annex.setFullName(procString(doc.getItemValueString("Fujm")));
                        }
                        annexService.saveOrUpdate(annex,ctx);

                        input.close();
                        os.flush();
                        os.close();
                    }
//                    Item Jiekbz=doc.getFirstItem("Jiekbz");
//                    Jiekbz.setValueString("1");
//                    doc.save();
                    doc = view.getNextDocument(doc);
                }
                view.recycle();
                oadb.recycle();
                session.recycle();
                System.out.println("end"+new Date());
            }
            catch (NotesException n)
            {
                n.printStackTrace();
            }
            catch (Exception e)
            {
                e.printStackTrace();
            }
        }

        public String procString(String source){
            if(source!=null&&source.indexOf(".")>-1&&source.indexOf("|")>-1&&source.indexOf("/")>-1){
                String temp=source.substring(source.indexOf("|")+1);
                String pre=temp.substring(0,temp.indexOf("/"));
                String sub=temp.substring(temp.indexOf("."));
                if(!"".equals(sub)){
                    return pre+sub;
                }
            }
            return source;
        }
        
    }

    public void contextInitialized(ServletContextEvent arg0)
    {
        // TODO Auto-generated method stub
        timer=new Timer(true);
        timer.schedule(new TimerTask(arg0.getServletContext()),0,60*1000*60*24);//每天
    }
    

    public void setSession(Session session)
    {
        this.session = session;
    }
    
    public Session getSession()
    {
        return session;
    }

    public void create(){
        
    }

    public String getMessage()
    {
        return message;
    }

    public void setMessage(String message)
    {
        this.message = message;
    }

}
